<template>
  <div class="container mx-auto px-4 py-8">
    <div class="flex flex-col lg:flex-row gap-8">
      <!-- 侧边栏 -->
      <div class="lg:w-64 flex-shrink-0">
        <!-- 用户信息概览 -->
        <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
          <div class="text-center mb-6">
            <el-avatar :size="80" :src="userInfo.avatar || userStore.defaultAvatar" />
            <h3 class="mt-4 text-lg font-semibold">{{ userInfo.nickname || userInfo.username }}</h3>
            <div v-if="userInfo.gender || userInfo.age" class="flex justify-center items-center gap-2 mt-2 text-sm text-gray-500">
              <span v-if="userInfo.gender">{{ userInfo.gender === 1 ? '男' : userInfo.gender === 2 ? '女' : '' }}</span>
              <span v-if="userInfo.age">{{ userInfo.age }}岁</span>
            </div>
            <p v-if="userInfo.school" class="text-gray-500 text-sm mt-1">{{ userInfo.school }}</p>
          </div>

          <!-- 导航菜单 -->
          <el-menu
            :default-active="activeMenu"
            class="border-none"
            @select="handleMenuSelect"
          >
            <el-menu-item index="todos">
              <el-icon><Calendar /></el-icon>
              <span>每日计划</span>
            </el-menu-item>
            <el-menu-item index="info">
              <el-icon><User /></el-icon>
              <span>个人信息</span>
            </el-menu-item>
            <el-menu-item index="security">
              <el-icon><Key /></el-icon>
              <span>账号安全</span>
            </el-menu-item>
            <el-menu-item index="comments">
              <el-icon><ChatRound /></el-icon>
              <span>我的评论</span>
            </el-menu-item>
            <el-menu-item index="replies">
              <el-icon><ChatDotRound /></el-icon>
              <span>评论回复</span>
            </el-menu-item>
          </el-menu>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="flex-grow">
        <!-- 每日计划TodoList -->
        <div v-if="activeMenu === 'todos'" class="bg-white rounded-lg shadow-sm p-6">
          <h2 class="text-xl font-semibold mb-6 flex items-center">
            <el-icon class="mr-2 text-blue-600"><Calendar /></el-icon>
            每日计划
          </h2>
          
          <!-- 添加新计划 -->
          <div class="flex items-center mb-6">
            <el-input 
              v-model="newTodoText" 
              placeholder="添加新计划..." 
              class="mr-2"
              @keyup.enter="addTodo"
            />
            <el-button 
              type="primary" 
              :icon="Plus" 
              @click="addTodo"
              :disabled="!newTodoText.trim()"
            >添加</el-button>
          </div>
          
          <!-- 计划进度 -->
          <div class="mb-6">
            <div class="flex justify-between items-center mb-2">
              <span class="text-gray-600">完成进度</span>
              <span class="font-medium">{{ completedTodoCount }}/{{ todos.length }}</span>
            </div>
            <el-progress 
              :percentage="todoProgressPercentage" 
              :format="() => ''" 
              :stroke-width="10"
              :color="todoProgressColor"
            />
          </div>
          
          <!-- 排序和筛选选项 -->
          <div class="flex justify-between items-center mb-4 text-sm">
            <div class="flex gap-3">
              <span 
                class="cursor-pointer hover:text-blue-600 transition-colors py-1 px-3 rounded-full"
                :class="{'bg-blue-50 text-blue-600': sortOrder === 'newest'}"
                @click="setSortOrder('newest')"
              >
                最新添加
              </span>
              <span 
                class="cursor-pointer hover:text-blue-600 transition-colors py-1 px-3 rounded-full"
                :class="{'bg-blue-50 text-blue-600': sortOrder === 'oldest'}"
                @click="setSortOrder('oldest')"
              >
                最早添加
              </span>
            </div>
            <div>
              <span 
                class="cursor-pointer hover:text-blue-600 transition-colors py-1 px-3 rounded-full"
                :class="{'bg-blue-50 text-blue-600': showCompleted}"
                @click="showCompleted = !showCompleted"
              >
                {{ showCompleted ? '隐藏已完成' : '显示已完成' }}
              </span>
            </div>
          </div>
          
          <!-- 计划列表 -->
          <div class="todos-container custom-scrollbar">
            <template v-if="filteredTodos.length">
              <div 
                v-for="(todo, index) in filteredTodos" 
                :key="todo.id || index"
                class="todo-item py-3 px-4 mb-3 rounded-lg hover:bg-blue-50 transition flex items-center justify-between group"
                :class="{'bg-blue-50': todo.completed}"
              >
                <div class="flex items-center flex-1 mr-2">
                  <el-checkbox 
                    v-model="todo.completed"
                    @change="updateTodoStatus(todo)"
                    class="custom-checkbox"
                  />
                  <span 
                    class="ml-3 transition-all duration-300"
                    :class="{'line-through text-gray-400': todo.completed, 'text-gray-700': !todo.completed}"
                  >
                    {{ todo.text }}
                  </span>
                </div>
                <el-button 
                  type="danger" 
                  :icon="Delete" 
                  circle 
                  size="small"
                  class="opacity-0 group-hover:opacity-100 transition-opacity duration-300"
                  @click="removeTodo(index)"
                ></el-button>
              </div>
            </template>
            <div v-else class="text-center py-12 text-gray-400 flex flex-col items-center">
              <el-icon class="mb-3 text-3xl"><DocumentAdd /></el-icon>
              <span>暂无计划，快来添加吧！</span>
            </div>
          </div>
          
          <!-- 完成所有计划后的鼓励语句 -->
          <div 
            v-if="todos.length > 0 && completedTodoCount === todos.length" 
            class="mt-6 p-4 bg-blue-50 text-blue-700 rounded-lg flex items-center animate-fade-in"
          >
            <el-icon class="mr-3 text-xl text-yellow-500"><Star /></el-icon>
            <span class="font-medium">太棒了！你已完成所有计划，继续保持！</span>
          </div>
        </div>
        
        <!-- 个人信息 -->
        <div v-else-if="activeMenu === 'info'" class="bg-white rounded-lg shadow-sm p-6">
          <h2 class="text-xl font-semibold mb-6">个人信息</h2>
          <el-form
            ref="formRef"
            :model="userForm"
            :rules="formRules"
            label-width="100px"
          >
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleAvatarChange"
                accept="image/jpeg,image/png,image/gif,image/jpg"
              >
                <img v-if="userForm.avatar" :src="userForm.avatar" class="w-24 h-24 rounded-full object-cover" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="用户名">
              <el-input v-model="userForm.username" disabled />
              <div class="text-xs text-gray-500 mt-1">用户名不可修改</div>
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="userForm.nickname" maxlength="20" show-word-limit />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="userForm.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
                <el-radio :label="0">保密</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄">
              <el-input-number v-model="userForm.age" :min="1" :max="120" />
            </el-form-item>
            <el-form-item label="学校" prop="school">
              <el-input v-model="userForm.school" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="userForm.phone" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSaveInfo">保存修改</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 账号安全 -->
        <div v-else-if="activeMenu === 'security'" class="bg-white rounded-lg shadow-sm p-6">
          <h2 class="text-xl font-semibold mb-6">账号安全</h2>
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="120px"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input 
                v-model="passwordForm.oldPassword" 
                type="password" 
                show-password
                placeholder="请输入当前密码" 
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="passwordForm.newPassword" 
                type="password" 
                show-password
                placeholder="请输入新密码" 
              />
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmNewPassword">
              <el-input 
                v-model="passwordForm.confirmNewPassword" 
                type="password" 
                show-password
                placeholder="请再次输入新密码" 
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdatePassword" :loading="passwordUpdating">更新密码</el-button>
            </el-form-item>
          </el-form>
          
          <div class="mt-8 pt-6 border-t border-gray-200">
            <h3 class="text-lg font-semibold mb-4">账号绑定</h3>
            <div class="space-y-4">
              <div class="flex justify-between items-center">
                <div class="flex items-center gap-3">
                  <el-icon class="text-blue-500"><Message /></el-icon>
                  <div>
                    <div class="font-medium">邮箱绑定</div>
                    <div class="text-gray-500 text-sm">{{ userInfo.email || '暂未绑定邮箱' }}</div>
                  </div>
                </div>
                <el-button type="primary" link>{{ userInfo.email ? '修改' : '绑定' }}</el-button>
              </div>
              
              <div class="flex justify-between items-center">
                <div class="flex items-center gap-3">
                  <el-icon class="text-green-500"><Iphone /></el-icon>
                  <div>
                    <div class="font-medium">手机绑定</div>
                    <div class="text-gray-500 text-sm">{{ userInfo.phone ? '已绑定手机：' + maskPhone(userInfo.phone) : '暂未绑定手机' }}</div>
                  </div>
                </div>
                <el-button type="primary" link>{{ userInfo.phone ? '修改' : '绑定' }}</el-button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 我的评论 -->
        <div v-else-if="activeMenu === 'comments'" class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-semibold">我的评论</h2>
            <el-button :loading="userStore.commentsLoading" @click="loadUserComments" type="primary" plain>
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
          
          <div v-if="userStore.commentsLoading" class="py-10 text-center">
            <el-icon class="is-loading text-2xl text-gray-400"><Loading /></el-icon>
            <p class="mt-2 text-gray-500">加载中...</p>
          </div>
          
          <div v-else-if="userStore.myComments.length === 0" class="py-10 text-center">
            <el-empty description="暂无评论" />
          </div>
          
          <div v-else>
            <div class="space-y-4">
              <div 
                v-for="(comment, index) in paginatedComments" 
                :key="index" 
                class="p-4 border rounded-lg hover:bg-gray-50"
              >
                <div class="flex justify-between items-start mb-2">
                  <div>
                    <h4 class="font-semibold mb-2">评论于：{{ comment.postTitle }}</h4>
                    <p class="text-gray-600">{{ comment.content }}</p>
                  </div>
                </div>
                <div class="text-sm text-gray-500">
                  {{ comment.createTime }}
                </div>
              </div>
            </div>
            
            <!-- 分页 -->
            <div class="flex justify-center mt-6" v-if="userStore.myComments.length > commentsPagination.pageSize">
              <el-pagination
                v-model:current-page="commentsPagination.currentPage"
                :page-size="commentsPagination.pageSize"
                :total="userStore.myComments.length"
                layout="prev, pager, next"
                @current-change="handleCommentsPageChange"
              />
            </div>
          </div>
        </div>
        
        <!-- 评论回复 -->
        <div v-else-if="activeMenu === 'replies'" class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-semibold">评论回复</h2>
            <el-button :loading="userStore.repliesLoading" @click="loadCommentReplies" type="primary" plain>
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
          
          <div v-if="userStore.repliesLoading" class="py-10 text-center">
            <el-icon class="is-loading text-2xl text-gray-400"><Loading /></el-icon>
            <p class="mt-2 text-gray-500">加载中...</p>
          </div>
          
          <div v-else-if="userStore.commentReplies.length === 0" class="py-10 text-center">
            <el-empty description="暂无回复" />
          </div>
          
          <div v-else>
            <div class="space-y-4">
              <div 
                v-for="(reply, index) in paginatedReplies" 
                :key="index" 
                class="p-4 border rounded-lg hover:bg-gray-50"
              >
                <div class="mb-4">
                  <div class="flex items-center gap-2 mb-2">
                    <el-avatar :size="24" :src="reply.author.avatar" />
                    <span class="font-semibold">{{ reply.author.name }}</span>
                    <span class="text-gray-500">回复了你的评论</span>
                  </div>
                  <p class="text-gray-600">{{ reply.content }}</p>
                </div>
                <div class="text-sm text-gray-500">
                  {{ reply.createTime }}
                </div>
              </div>
            </div>
            
            <!-- 分页 -->
            <div class="flex justify-center mt-6" v-if="userStore.commentReplies.length > repliesPagination.pageSize">
              <el-pagination
                v-model:current-page="repliesPagination.currentPage"
                :page-size="repliesPagination.pageSize"
                :total="userStore.commentReplies.length"
                layout="prev, pager, next"
                @current-change="handleRepliesPageChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  ChatRound,
  ChatDotRound,
  Plus,
  Loading,
  Refresh,
  Key,
  Message,
  Iphone,
  Calendar,
  Delete,
  Star,
  DocumentAdd
} from '@element-plus/icons-vue'

// 获取用户store
const userStore = useUserStore()
const router = useRouter()

// 当前选中的菜单
const activeMenu = ref('todos')

// 用户信息，从store中获取
const userInfo = computed(() => userStore.getUserProfile)

// 表单数据，克隆用户信息到表单
const userForm = ref({
  username: '',
  nickname: '',
  avatar: '',
  school: '',
  gender: 1,
  age: 20,
  email: '',
  phone: '',
  avatarFile: null
})

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmNewPassword: ''
})

// 密码更新状态
const passwordUpdating = ref(false)

// 我的评论分页
const commentsPagination = ref({
  currentPage: 1,
  pageSize: 5
})

// 我的回复分页
const repliesPagination = ref({
  currentPage: 1,
  pageSize: 5
})

// 表单引用
const formRef = ref(null)
const passwordFormRef = ref(null)

// 分页后的评论列表
const paginatedComments = computed(() => {
  const startIndex = (commentsPagination.value.currentPage - 1) * commentsPagination.value.pageSize
  const endIndex = startIndex + commentsPagination.value.pageSize
  return userStore.myComments.slice(startIndex, endIndex)
})

// 分页后的回复列表
const paginatedReplies = computed(() => {
  const startIndex = (repliesPagination.value.currentPage - 1) * repliesPagination.value.pageSize
  const endIndex = startIndex + repliesPagination.value.pageSize
  return userStore.commentReplies.slice(startIndex, endIndex)
})

// 手机号码遮掩函数
const maskPhone = (phone) => {
  if (!phone || phone.length !== 11) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 初始化用户表单
const initUserForm = () => {
  const info = userStore.getUserProfile
  userForm.value = {
    username: info.username || '',
    nickname: info.nickname || '',
    avatar: info.avatar || '',
    school: info.school || '',
    gender: info.gender || 0,
    age: info.age || '',
    email: info.email || '',
    phone: info.phone || '',
    avatarFile: null
  }
}

// 重置表单
const resetForm = () => {
  initUserForm()
  ElMessage.info('表单已重置')
}

// 表单校验规则
const formRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  school: [
    { required: true, message: '请输入学校', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ]
}

// 密码校验规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
  ],
  confirmNewPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 处理菜单选择
const handleMenuSelect = async (key) => {
  activeMenu.value = key
  
  if (key === 'comments') {
    await loadUserComments()
  } else if (key === 'replies') {
    await loadCommentReplies()
  }
}

// 加载用户评论
const loadUserComments = async () => {
  try {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录后查看我的评论')
      activeMenu.value = 'info'
      return
    }
    
    await userStore.fetchMyComments()
    
    // 重置到第一页
    commentsPagination.value.currentPage = 1
  } catch (error) {
    console.error('加载用户评论出错:', error)
    ElMessage.error('获取评论失败')
  }
}

// 加载评论回复
const loadCommentReplies = async () => {
  try {
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录后查看评论回复')
      activeMenu.value = 'info'
      return
    }
    
    await userStore.fetchCommentReplies()
    
    // 重置到第一页
    repliesPagination.value.currentPage = 1
  } catch (error) {
    console.error('加载评论回复出错:', error)
    ElMessage.error('获取评论回复失败')
  }
}

// 处理头像更改
const handleAvatarChange = (file) => {
  // 保存原始文件对象用于后续上传
  userForm.value.avatarFile = file.raw
  // 设置本地预览
  userForm.value.avatar = URL.createObjectURL(file.raw)
}

// 处理保存个人信息
const handleSaveInfo = async () => {
  try {
    // 表单验证
    await formRef.value.validate()

    // 构建用于更新的数据对象
    const updateData = {}
    
    // 用户ID是必需的
    updateData.userId = userInfo.value.userId

    // 只包含有值的字段
    if (userForm.value.nickname) updateData.nickname = userForm.value.nickname
    // 传递原始文件对象和展示用的URL
    if (userForm.value.avatarFile) updateData.avatarFile = userForm.value.avatarFile
    if (userForm.value.avatar) updateData.avatar = userForm.value.avatar
    if (userForm.value.school !== undefined) updateData.school = userForm.value.school
    if (userForm.value.gender !== undefined) updateData.gender = userForm.value.gender
    if (userForm.value.age !== undefined) updateData.age = userForm.value.age
    if (userForm.value.email) updateData.email = userForm.value.email
    if (userForm.value.phone) updateData.phone = userForm.value.phone
    
    // 调用store的更新方法，使用新的API
    const success = await userStore.updateUserInfo(updateData)
    
    if (success) {
      ElMessage.success('信息更新成功')
    } else {
      ElMessage.error('信息更新失败')
    }
  } catch (error) {
    console.error('表单验证或保存出错:', error)
    ElMessage.error('保存失败:' + (error.message || '未知错误'))
  }
}

// 处理密码更新
const handleUpdatePassword = async () => {
  try {
    // 表单验证
    await passwordFormRef.value.validate()

    passwordUpdating.value = true
    const success = await userStore.changePassword({
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword,
      confirmPassword: passwordForm.value.confirmNewPassword
    })
    
    if (success) {
      ElMessage.success('密码修改成功，请重新登录')
      // 清除表单
      passwordForm.value = {
        oldPassword: '',
        newPassword: '',
        confirmNewPassword: ''
      }
      // 退出登录，重定向到登录页
      setTimeout(() => {
        userStore.logout()
      }, 1500)
    } else {
      ElMessage.error('密码修改失败，请检查当前密码是否正确')
    }
  } catch (error) {
    console.error('密码更新出错:', error)
    ElMessage.error('密码修改失败: ' + (error.message || '未知错误'))
  } finally {
    passwordUpdating.value = false
  }
}

// 处理评论分页变化
const handleCommentsPageChange = (page) => {
  commentsPagination.value.currentPage = page
}

// 处理回复分页变化
const handleRepliesPageChange = (page) => {
  repliesPagination.value.currentPage = page
}

// TodoList 功能
const newTodoText = ref('')
const todos = ref([])
const sortOrder = ref('newest') // 排序方式：newest, oldest
const showCompleted = ref(true) // 是否显示已完成任务

// 从本地存储加载待办事项
const loadTodos = () => {
  const savedTodos = localStorage.getItem('userTodos')
  if (savedTodos) {
    todos.value = JSON.parse(savedTodos)
    // 确保每个任务都有唯一ID
    todos.value.forEach(todo => {
      if (!todo.id) todo.id = Date.now() + Math.random().toString(36).substr(2, 9)
    })
  }
}

// 过滤和排序后的待办事项
const filteredTodos = computed(() => {
  // 先筛选
  let result = showCompleted.value 
    ? todos.value 
    : todos.value.filter(todo => !todo.completed)
  
  // 再排序
  return result.sort((a, b) => {
    if (sortOrder.value === 'newest') {
      return b.createTime - a.createTime
    } else {
      return a.createTime - b.createTime
    }
  })
})

// 设置排序方式
const setSortOrder = (order) => {
  sortOrder.value = order
}

// 保存待办事项到本地存储
const saveTodos = () => {
  localStorage.setItem('userTodos', JSON.stringify(todos.value))
}

// 已完成的待办事项数量
const completedTodoCount = computed(() => {
  return todos.value.filter(todo => todo.completed).length
})

// 完成进度百分比
const todoProgressPercentage = computed(() => {
  if (todos.value.length === 0) return 0
  return Math.round((completedTodoCount.value / todos.value.length) * 100)
})

// 进度条颜色
const todoProgressColor = computed(() => {
  const percentage = todoProgressPercentage.value
  if (percentage < 30) return '#909399'
  if (percentage < 70) return '#409EFF'
  if (percentage < 100) return '#67C23A'
  return '#E6A23C'
})

// 添加新待办事项
const addTodo = () => {
  if (!newTodoText.value.trim()) return
  
  todos.value.unshift({
    id: Date.now() + Math.random().toString(36).substr(2, 9),
    text: newTodoText.value.trim(),
    completed: false,
    createTime: new Date().getTime()
  })
  
  newTodoText.value = ''
  saveTodos()
}

// 更新待办事项状态
const updateTodoStatus = (todo) => {
  saveTodos()
}

// 删除待办事项
const removeTodo = (index) => {
  todos.value.splice(index, 1)
  saveTodos()
}

// 监听待办事项变化，保存到本地存储
watch(todos, () => {
  saveTodos()
}, { deep: true })

// 组件挂载时初始化数据
onMounted(async () => {
  // 确保用户已登录，否则获取用户信息
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录查看个人资料')
    router.push('/auth/login')
    return
  }
  
  // 如果已登录但没有用户信息，尝试获取
  if (!userStore.userInfo) {
    try {
      const success = await userStore.fetchUserInfo()
      if (!success) {
        ElMessage.warning('获取用户信息失败，请重新登录')
        router.push('/auth/login')
        return
      }
    } catch (error) {
      console.error('获取用户信息错误:', error)
      ElMessage.error('获取用户信息失败')
      router.push('/auth/login')
      return
    }
  }
  
  // 初始化表单数据
  initUserForm()
  
  // 只在登录情况下才加载初始选项卡数据
  if (userStore.isLoggedIn) {
    if (activeMenu.value === 'comments') {
      await loadUserComments()
    } else if (activeMenu.value === 'replies') {
      await loadCommentReplies()
    }
  }
  
  loadTodos()
})
</script>

<style scoped>
.avatar-uploader {
  display: flex;
  justify-content: center;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 96px;
  height: 96px;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* TodoList 自定义样式 */
.todos-container {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 1.5rem;
}

.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.1) transparent;
}

.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.2);
}

.custom-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #4d7cfe;
  border-color: #4d7cfe;
}

.todo-item {
  border-left: 3px solid transparent;
  transition: all 0.2s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.todo-item:hover {
  border-left-color: #4d7cfe;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.todo-item.completed {
  border-left-color: #67C23A;
}

.animate-fade-in {
  animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style> 